/**
 * Copyright (c) 2005-2012 https://github.com/zhangkaitao
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.xb.loan.admin.web.filter;

import com.xb.loan.admin.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;


/**
 * 类  描  述 : 验证码校验过滤器
 */
public class AuthCodeValidateFilter extends AccessControlFilter {

    private boolean authCodeEnabled = true;//是否开启验证码支持

    private String authCodeParam = "authCode";//前台提交的验证码参数名

    private String failureKeyAttribute = "shiroLoginFailure"; //验证码验证失败后存储到的属性名

    public void setAuthCodeEnabled(boolean authCodeEnabled) {
        this.authCodeEnabled = authCodeEnabled;
    }
    public void setAuthCodeParam(String authCodeParam) {
        this.authCodeParam = authCodeParam;
    }
    public void setFailureKeyAttribute(String failureKeyAttribute) {
        this.failureKeyAttribute = failureKeyAttribute;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        //1、设置验证码是否开启属性，页面可以根据该属性来决定是否显示验证码
        
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        
        //3、此时是表单提交，验证验证码是否正确
        
        HttpSession session=httpServletRequest.getSession();
        
        String sessionAuthCode=(String)session.getAttribute(Constants.SESSION_AUTHCODE);
        
        Enumeration<String> se = session.getAttributeNames();
        while (se.hasMoreElements()) {
			String string = (String) se.nextElement();
			if(!Constants.SESSION_AUTHCODE.equals(string)){
				session.removeAttribute(string);
			}
		}
        //session.setAttribute(Constants.SESSION_AUTHCODE,sessionAuthCode);
        
        //2、判断验证码是否禁用 或不是表单提交（允许访问） 
        if (!authCodeEnabled || !"post".equalsIgnoreCase(httpServletRequest.getMethod())) {
            return true;
        }
        
        String requestAuthCode=httpServletRequest.getParameter(authCodeParam);
        if(StringUtils.isBlank(sessionAuthCode) || StringUtils.isBlank(requestAuthCode)){
        	 return false;
        }
        //判断是否相同
        return sessionAuthCode.equalsIgnoreCase(requestAuthCode);
    }
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //如果验证码失败了，存储失败key属性
        request.setAttribute(failureKeyAttribute, "authCodeError");
        return true;
    }
}
